import 'package:old_shop/common/const/cosnt.dart';
import 'package:dio/dio.dart';

enum HTTPMETHOD { GET, POST, PUT, DELETE }

class Networktool {
  static String baseURL = AppConst.APP_IS_RELEASE ? "https://picsum.photos/" : "https://picsum.photos/";
  static request(String url,
      {HTTPMETHOD method = HTTPMETHOD.POST,
      Map<String, dynamic>? params,
      Function? success,
      Function(String msg)? fail,
      Function? finaly}) async {
    late Response response;
    url = baseURL + url;
    print("api = $url, param = $params, method:$method");

    // SharedPreferences share = await SharedPreferences.getInstance();
    // String token = share.getString(KEY_user_token);

    Options options = Options(receiveTimeout: 1000000);
    // if(token != null){
    //   print("token = $token");
    //   options = Options(
    //     headers: {"token": token}
    //   );
    // }

    try {
      switch (method) {
        case HTTPMETHOD.POST:
          FormData formData = FormData.fromMap(params ?? {});
          response = await Dio().post(url, data: formData, options: options);
          break;
        case HTTPMETHOD.GET:
          if (params == null) params = {};
          response = await Dio().get(url, queryParameters: params, options: options);
          break;
        case HTTPMETHOD.PUT:
          response = await Dio().put(url, data: params, options: options);
          break;
        case HTTPMETHOD.DELETE:
          response = await Dio().delete(url, data: params, options: options);
          break;
        default:
      }
    } catch (e) {
      if (finaly != null) finaly();
      print(e.toString());
      if (fail != null) fail(e.toString());
    }

    if (finaly != null) finaly();
    print("url = $url, data = ${response.data}");
    String code = response.headers.value("statuscode").toString();
    if (response.statusCode == 200) {
      if (success != null) success(response.data);
    } else {
      if (fail != null) {
        if (response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }
}
